import { gameState } from './state.js';
import { Player } from './player.js';
import { Enemy } from './enemy.js';
import { addCombatLog } from './ui.js';

export function autoAttack() {
    Enemy.currentHealth -= Player.attack;
    addCombatLog(`玩家攻击敌人 (${Player.attack}伤害)`);

    if (Enemy.currentHealth <= 0) {
        handleEnemyDeath();
    } else {
        handleEnemyCounterAttack();
    }

    checkPlayerStatus();
}

function handleEnemyDeath() {
    gameState.setGold(gameState.gold + Enemy.level * 5); // 使用setter方法
    Enemy.remaining--;
    addCombatLog(`击败敌人! 获得 ${Enemy.level * 5}金币`);

    if (Enemy.remaining <= 0) {
        nextLayer();
    } else {
        Enemy.spawnNew();
    }
}

function handleEnemyCounterAttack() {
    Player.currentHealth -= Enemy.attack;
    addCombatLog(`敌人反击 (${Enemy.attack}伤害)`);
}

function nextLayer() {
    gameState.currentLayer++;
    Enemy.init(gameState.currentLayer);
    addCombatLog(`=== 进入第 ${gameState.currentLayer} 层! ===`);
}

function checkPlayerStatus() {
    if (Player.currentHealth <= 0) {
        handlePlayerDeath();
    }
}

function handlePlayerDeath() {
    if (gameState.currentLayer > 1) {
        gameState.currentLayer--;
        addCombatLog(`玩家死亡! 掉落到第 ${gameState.currentLayer} 层`);
    } else {
        addCombatLog(`玩家死亡! 停留在第 1 层`);
    }
    Player.init();
    Enemy.init(gameState.currentLayer);
}